import { sm4 } from 'sm-crypto'
const key = '157772cfb4d74316d8f6d2c7416fbd10'

// 将16进制字符串转为base64
function hexToBase64(hexString: string) {
  // 将16进制字符串转换为字节数组
  const byteArray = hexStringToByteArray(hexString)
  // 将字节数组转换为base64字符串
  const base64String = btoa(String.fromCharCode(...byteArray))
  return base64String
}

// 将16进制字符串转换为字节数组
function hexStringToByteArray(hexString: string) {
  const byteArray = []
  for (let i = 0; i < hexString.length; i += 2) {
    const byte = parseInt(hexString.substr(i, 2), 16)
    byteArray.push(byte)
  }
  return byteArray
}

export const SM_Encrypt = (plaintext: any) => {
  // 这段代码首先将16进制字符串转换为字节数组，然后使用JavaScript内置的btoa()函数将字节数组编码为base64字符串。在此示例中，我们
  let encryptData = sm4.encrypt(plaintext, key) // 加密，默认输出 16 进制字符串，默认使用 pkcs#7 填充（传 pkcs#5 也会bc 模式
  encryptData = encryptData.toUpperCase() // 将16进制字符串转大写
  encryptData = hexToBase64(encryptData)

  return encryptData
}

function base64ToHex(base64: any) {
  const binaryStr = atob(base64)
  let hexStr = ''
  for (let i = 0; i < binaryStr.length; i++) {
    const hex = binaryStr.charCodeAt(i).toString(16)
    hexStr += (hex.length === 1 ? '0' : '') + hex
  }
  return hexStr
}

export const SM_Decrypt = (plaintext: any) => {
  let decryptData = base64ToHex(plaintext)
  decryptData = decryptData.toLowerCase() // 得到小写
  decryptData = sm4.decrypt(decryptData, key)
  return decryptData
}
